package org.example.template.aspect;



import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.template.annotation.MyAnnotation;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class InterfaceLogAspect {
    // 配置切入点
    @Pointcut("@annotation(org.example.template.annotation.MyAnnotation)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object aroundBusAsMethod(ProceedingJoinPoint joinPoint) {
        // 获得注解
        MyAnnotation controllerLog = getAnnotationLog(joinPoint);
        Object[] args = joinPoint.getArgs();
        Object respObj = null;
        long startTime = System.currentTimeMillis();
        try {
            respObj = joinPoint.proceed(args);
        } catch (Throwable e) {
            log.error("获取方法响应异常，原因：{}", e.toString());
        }
        long endTime = System.currentTimeMillis();
        log.info("Method {} execution time: {}ms", joinPoint.getSignature().getName(), endTime - startTime);
        log.info(controllerLog.title());

        //log.info(JSONObject.toJSONString(respObj));
        return respObj;
    }
    @Before(value = "execution(* org.example.template.controller.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("Request URL: {} {}", request.getMethod(), request.getRequestURL());
        if(request.getMethod().equals("GET")){
            for (String key:request.getParameterMap().keySet()
                 ) {
                log.info("参数为{}={}",key,request.getParameterMap().get(key)[0]);
            }
        }
        log.info("Request parameters: {}", request.getParameterMap());
    }
    /**
     * 是否存在注解，如果存在就获取
     */
    private MyAnnotation getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(MyAnnotation.class);
        }
        return null;
    }

}
